package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;

import com.alibaba.fastjson.JSONObject
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import groovy.json.*;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import cn.com.kh.getProperty;


/*
 * @purpose: 腾讯云短信发送接口
 * @示例报文：
 * */

public class apitext implements ServiceBackInvoke{

	private static final Log log=LogFactory.getLog(apitext.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){


		log.debug("----------------------------------start BP_job_SmsSend from 开始发送短信 -----------------------------");//日志标识，方便查找
		//判断是否有需要发送的短信
		def getSmsSelectSQL = eliteBean.chaxun_sql("select DOCUMENTOUT_GUID,DOCUMENTTO,model_id as templateId,model_1 as msg_1,model_2 as msg_2,model_3 as msg_3,model_4 as msg_4 from documentout where ExpectedStartDate<=GETDATE() and STATUS=0","dataSource");
		log.debug("SQL获取数据:"+getSmsSelectSQL);
		if(getSmsSelectSQL.size() > 0) {
			log.debug("BP_job_SmsSend开始处理短信发送任务--------------------------");
			//获取配置信息
			int apiid = Integer.parseInt(getProperty.get("SMS.AppID"));
			String apikey = getProperty.get("SMS.AppKey");
			String smsSign = "宝安排水"; // 签名
			log.debug("apiid:" + apiid+"	apikey:" + apikey);

			boolean sendMsgResult=false; //短信发送结果
			String cloudResponseStr=""; //腾讯云返回结果
			def returnMessage='';//返回信息
			def returnDealFlag="";//响应标识 1 成功，0 失败
			def returnDealMessage="";//响应信息

			String documentOutGUID="";//documentout表，主键，用于更新数据
			String DOCUMENTTO="";//手机号码
			int templateId=0;////腾讯云短信模板ID
			String msg_1 =""; //内容参数1
			String msg_2 =""; //内容参数2
			String msg_3 =""; //内容参数3
			String msg_4 =""; //内容参数4
			try{
				for(int i=0;i<getSmsSelectSQL.size();i++) {
					documentOutGUID = getSmsSelectSQL.get(i).get("DOCUMENTOUT_GUID");
					DOCUMENTTO= getSmsSelectSQL.get(i).get("DOCUMENTTO");
					templateId=Integer.parseInt(getSmsSelectSQL.get(i).get("templateId"));;
					msg_1 =getSmsSelectSQL.get(i).get("msg_1");
					msg_2 =getSmsSelectSQL.get(i).get("msg_2");
					msg_3 =getSmsSelectSQL.get(i).get("msg_3");
					msg_4 =getSmsSelectSQL.get(i).get("msg_4");

					ArrayList<?> docParams = new ArrayList<?>();
					if(templateId==680764) {
						docParams.add(msg_1);
					}else if(templateId==680766) {
						docParams.add(msg_1);
						docParams.add(msg_2);
						docParams.add(msg_3);
						docParams.add(msg_4);
					}else if(templateId==680767) {
						docParams.add(msg_1);
						docParams.add(msg_2);
						docParams.add(msg_3);
						docParams.add(msg_4);
					}else if(templateId==680768) {
						docParams.add(msg_1);
						docParams.add(msg_2);
						docParams.add(msg_3);
					}else if(templateId==680769) {
						docParams.add(msg_1);
						docParams.add(msg_2);
						docParams.add(msg_3);
					}else if(templateId==680770) {
						docParams.add(msg_1);
						docParams.add(msg_2);
					}else if(templateId==680771) {
						docParams.add(msg_1);
						docParams.add(msg_2);
					}

						try {

							SmsSingleSender ssender = new SmsSingleSender(apiid, apikey);
							// 签名参数未提供或者为空时，会使用默认签名发送短信
							SmsSingleSenderResult result = ssender.sendWithParam("86", DOCUMENTTO, templateId, docParams, smsSign, "", "");
							//String result="{\"result\":0,\"errmsg\":\"OK\",\"ext\":\"\",\"sid\":\"2019:-9004554355786506379\",\"fee\":1,\"isocode\":\"CN\"}";
							
							log.info("result:"+result);

							cloudResponseStr=result.toString();

							JSONObject reponseBodyJsonObject = JSONObject.parseObject(cloudResponseStr);
							String resultCode = reponseBodyJsonObject.getString("result");
							String resultMsg = reponseBodyJsonObject.getString("errmsg");

							if("0".equals(resultCode)) {
								sendMsgResult=true;
								returnDealMessage="腾讯云短信发送成功！";
							} else {
								sendMsgResult=false;
								returnDealMessage="腾讯云短信发送失败！"+java.net.URLDecoder.decode(resultMsg);
							}
						} catch (HTTPException e) {
							// HTTP响应码错误
							sendMsgResult=false;
							returnDealMessage="HTTP响应码错误!";
							e.printStackTrace();
						} catch (JSONException e) {
							// json解析错误
							sendMsgResult=false;
							returnDealMessage="json解析错误!";
							e.printStackTrace();
						} catch (IOException e) {
							// 网络IO错误
							sendMsgResult=false;
							returnDealMessage="网络IO错误!";
							e.printStackTrace();
						}
					
				}

			} catch(SAXParseException) {
				log.error("异常",SAXParseException); //打印日志
				returnDealFlag="0";
				returnDealMessage="电销系统:接收的请求报文格式错误,无法解析数据!";
			}
			if(sendMsgResult) {
				returnDealFlag="1";
			}else {
				returnDealFlag="0";
			}

			returnMessage="""{"dealFlag":"${returnDealFlag}","dealMessage":"${returnDealMessage}","cloudResponse":${cloudResponseStr}}""";

			eliteBean.update("update DocumentOut set response_msg = '"+returnMessage+"',Status = '"+returnDealFlag+"',TrialCount = TrialCount+1,LastTryDateTime=GETDATE(),FinishDateTime=GETDATE(),ModifiedDate=GETDATE()  where DocumentOut_GUID = '"+documentOutGUID+"'", "dataSource");
			log.debug("returnMessage:" + returnMessage+"	Status:" + returnDealFlag+"	documentOutGUID:" + documentOutGUID);			
								
			return returnMessage;
			
		}
		log.debug("BP_job_SmsSend当前无短信发送任务--------------------------");

	}

}
